package com.example.gobang.controller;

import com.example.gobang.constant.Constants;
import com.example.gobang.mapper.UserMapper;
import com.example.gobang.model.Result;
import com.example.gobang.model.User;
import com.example.gobang.utils.JWTUtils;
import com.example.gobang.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserMapper mapper;

    @RequestMapping("/login")
    public Result<String> login(HttpSession session, String username, String password){
        User user = mapper.selectUserByName(username);
        if(user == null){
            log.info("登录失败......");
            return Result.fail("用户不存在");
        }
        if(!SecurityUtils.verity(password, user.getPassword())){
            log.info("登录失败......");
            return Result.fail("用户名或密码错误");
        }
        log.info("登录成功 用户 " + user.getUsername());
        Map<String, Object> secret = new HashMap<>();
        secret.put(Constants.TOKEN_USERINFO, user);
        session.setAttribute("user", user);
        secret.put(Constants.TOKEN_USERNAME, user.getUsername());
        String token = JWTUtils.generateToken(secret);
        return Result.success(token);
    }

    @RequestMapping("/register")
    public User register(String username, String password){
        User user = new User();
        try {
            user.setUsername(username);
            user.setPassword(SecurityUtils.encrypt(password));
            mapper.insert(user);
        } catch (Exception e){
            return null;
        }
        return user;
    }

    @RequestMapping("/getUserInfo")
    public User getUserInfo(HttpServletRequest request){
        try {
            String token = request.getHeader(Constants.HEADER_TOKEN);
            String userName = JWTUtils.getUserNameByToken(token);
            return mapper.selectUserByName(userName);
        } catch (NullPointerException e){
            return null;
        }
    }
}
